<template>
  <dtDialog
    :title="textMap"
    :visible.sync="DialogFormVisible"
    :is-loading="loading"
    @closeDialog="resetTemp()"
    @comfirmBtn="onSubmit()"
  >
    <el-form
      ref="codeForm"
      slot="content"
      :rules="rules"
      :model="tempForm"
      label-position="right"
      label-width="68px"
    >
      <el-form-item label="数据源" prop="dbId">
        <el-select ref="tenantId" v-model.trim="tempForm.dbId" placeholder="请选择数据源"
                   clearable style="width: 100%;" @change="changeDBName">
          <el-option
            v-for="item in dataList"
            :key="item.dbId"
            :label="item.dbName"
            :value="item.dbId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="表名" prop="tableNameObj">
        <el-select v-model.trim="tableNameObj" multiple value-key="tableName"
                   placeholder="请选择表名" clearable style="width:100%;">
          <el-option
            v-for="item in tableList"
            :key="item.tableName"
            :label="item.tableName"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="包名" prop="packageName">
        <el-input v-model.trim="tempForm.packageName" maxlength="50" placeholder="请输入包名"
                  show-word-limit class="limit" />
      </el-form-item>
      <el-form-item label="作者" prop="author">
        <el-input v-model.trim="tempForm.author" maxlength="50" placeholder="请输入作者"
                  show-word-limit class="limit" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model.trim="tempForm.remark" maxlength="100" placeholder="请输入备注"
                  type="textarea" show-word-limit class="limit" />
      </el-form-item>
    </el-form>
  </dtDialog>
</template>
<script>
import codeGenerationApi from '@/framework/api/codeGeneration'
import { packageName } from '@/framework/utils/validate'
import { toCamal, upperCamelCase } from '@/framework/utils/index'

const formatToHump = (value) => {
  // 生成服务名生成规则：根据表名例如A_B_C， 服务名为：/ABC 注意BC要驼峰，具体实例表名是hr_organization_copy1_copy1 ，服务名是/hrOrganizationCopy1Copy1
  // eslint-disable-next-line no-useless-escape
  return `/${value.replace(/\_(\w)/g, (_, letter) => letter.toUpperCase())}`
}
export default {
  data() {
    return {
      DialogFormVisible: false,
      textMap: '批量新增',
      dataList: '',
      tableList: '',
      tableNameObj: {},
      tempForm: {
        dbId: '',
        packageName: 'com.hbisdt.dqbasic.modular',
        author: '',
        remark: '',
        moduleName: '',
        businessName: '',
        serviceName: '',
        tableComment: ''
      },
      moreTables: [],
      rules: {
        dbId: [{ required: true, trigger: 'change', message: '请选择数据源' }],
        tableNameObj: [{
          required: true,
          trigger: 'change',
          validator: (rule, value, callback) => {
            if (this.tableNameObj.length <= 0) {
              callback(new Error('请输入表名'))
            } else {
              callback()
            }
          }
        }],
        packageName: [{ required: true,
          trigger: 'change',
          validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error('请输入包名'))
            } else if (!packageName(value)) {
              callback(new Error('包名必须以英文字母开头、包含字母和"."'))
            } else {
              callback()
            }
          }
        }]
      },
      loading: false,
      editUservisible: false
    }
  },
  methods: {
    // 关闭弹窗
    resetTemp() {
      this.$nextTick(() => {
        this.$refs['codeForm'].resetFields()
        this.tableNameObj = {}
      })
    },
    // 打开新增弹窗
    open() {
      this.DialogFormVisible = true
      // 获取下拉数据源和表名的数据
      codeGenerationApi.list().then((res) => {
        this.dataList = res.data
      })
      this.$nextTick(() => {
        this.$refs.codeForm.clearValidate()
      })
    },
    changeDBName() {
      this.tableList = []
      codeGenerationApi.getTablesInfo({ dbId: this.tempForm.dbId }).then((res) => {
        this.tableList = res.data
      })
      this.$nextTick(() => {
        this.$refs.codeForm.clearValidate('tenantId')
      })
    },
    // 批量新增请求
    async onSubmit() {
      this.$refs['codeForm'].validate(async (valid) => {
        if (valid) {
          this.loading = true
          this.moreTables = this.tableNameObj.map((item) => {
            const { tableName } = item
            const businessName = [...tableName.split('_')[1]]
            businessName[0] = businessName[0].toUpperCase()
            return { ...this.tempForm, tableName, businessName: upperCamelCase(toCamal(tableName)), serviceName: formatToHump(tableName), moduleName: toCamal(tableName), tableComment: item.tableComment, schemaName: item.tableSchema }
          })
          try {
            // const res = await codeGenerationApi.addMore(tempData)
            const res = await codeGenerationApi.addMore(this.moreTables)
            if (res.success) {
              this.$parent.getList()
              this.DialogFormVisible = false
              this.$dtMessage({
                message: '新增成功',
                type: 'success'
              })
            }
            this.loading = false
          } catch (error) {
            this.loading = false
          }
        }
      })
    }
  }
}
</script>
